/**
 * 时间转时间戳
 * 格式 '2021-11-7' 或者'2021-11-7 12:10:19'
 * @param time
 * @type string
 * @return number
 * */
export function timeToTimestamp(time:string | number) {
  return new Date(time).getTime();
}

/**
 * 时间戳转时间
 * 返回格式 2021-10-03
 * @param time
 */
export const timestampToTime = (time:string | number) => {
  let date = new Date(time);
  let Year = date.getFullYear() + '-';
  let Month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '';
  return Year + Month + Day;
};

/**
 * 时间戳转时间(ms)
 * 返回格式 2021-11-03 19:16:04
 * @param time
 */
export const toDetailTime = (time:string | number) => {
  let date = new Date(time);
  let Year = date.getFullYear() + '-';
  let Month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return Year + Month + Day + h + m + s;
};


/**
 * 时间戳计算年龄
 * 传入出生的时间戳返回年龄
 * @param birthday
 */
export const getTimestampToAge = (birthday:string | number) => {
  //出生时间 毫秒
  let birthDayTime = new Date(birthday).getTime();
  //当前时间 毫秒
  let nowTime = new Date().getTime();
  //一年毫秒数(365 * 86400000 = 31536000000)
  return Math.ceil((nowTime - birthDayTime) / 31536000000) - 1;
};


/**
 * 计算年龄
 * 格式 '2019-06-06'
 * @param time
 */
export const getAge = (time:string) => {
  const info:Array<any> = time.split('-');
  const date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let age = year - info[0];
  if (month < info[1]) --age;
  if (month === info[1] && day < info[2]) --age;
  if (age < 0 && isNaN(Number(time))) return 0;
  return age;
};


